<template>
  <el-dialog
    title="批量调度"
    width="1800px"
    :visible.sync="dialogTableVisible"
    v-dialogDrag
    :close-on-click-modal="false"
    @closed="closedDialog"
    v-loading="isLoading"
    customClass="mes_dialog">
    <div class="table_container">
      <el-table
        class="table_dialog workstage_scdu"
        :data="workstageList"
        height="440"
        border
        style="width: 100%"
        tooltip-effect="dark">
        <mes-col-comp :key="index" v-for="(column, index) in tableColums" :column="column"></mes-col-comp>
        <el-table-column
          prop="planStartDate"
          label="工序计划开始时间"
          align="center"
          width="160">
          <template slot-scope="scope">
            <div class="plane_startTime">
              <el-date-picker
                :clearable="false"
                v-model="scope.row.planStartDate"
                align="right"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd 00:00:00"
                :picker-options="getPickerOptionsStart(scope.row.planEndDate)">
              </el-date-picker>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="planEndDate"
          label="工序计划完成时间"
          align="center"
          width="160">
          <template slot-scope="scope">
            <div class="plane_endTime">
              <el-date-picker
                :clearable="false"
                v-model="scope.row.planEndDate"
                align="right"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd 23:59:59"
                :picker-options="getPickerOptionsEnd(scope.row.planStartDate)">
              </el-date-picker>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :class-name="'table_select'"
          label="执行班组"
          prop="workgroupId"
          width="200">
          <template slot-scope="scope">
            <el-select
              filterable
              placeholder="请选择"
              v-model="scope.row.workgroupId"
              class="type_list"
              @change="workgroupChange(scope.row)">
              <el-option
                v-for="item in scope.row.nametree"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          :class-name="'table_select'"
          prop="workcenterId"
          label="工作中心"
          width="200">
          <template slot-scope="scope">
            <el-select
              filterable
              placeholder="请选择"
              v-model="scope.row.workcenterId"
              class="type_list"
              popper-class="disabled_select"
              @change="workcenterChange(scope.row)">
              <el-option
                v-for="item in scope.row.workCenterList"
                :disabled="item.useFlag === '0'"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          :class-name="'table_select'"
          prop="deviceIds"
          label="设备"
          width="200">
          <template slot-scope="scope">
            <el-select
              v-if="multipleStatus"
              filterable
              multiple
              collapse-tags
              :multiple-limit="100"
              placeholder="请选择"
              v-model="scope.row.deviceIds"
              popper-class="disabled_select"
              class="type_list"
              @remove-tag="removeTagSelect(scope.row, 'device')">
              <el-option
                v-for="item in scope.row.deviceList"
                :disabled="item.useFlag === '0'"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          :class-name="'table_select'"
          prop="staffIds"
          label="人员"
          width="200">
          <template slot-scope="scope">
            <el-select
              v-if="multipleStatus"
              filterable
              multiple
              collapse-tags
              :multiple-limit="100"
              placeholder="请选择"
              v-model="scope.row.staffIds"
              popper-class="disabled_select"
              class="type_list"
              @remove-tag="removeTagSelect(scope.row, 'staff')">
              <el-option
                v-for="item in scope.row.staffList"
                :disabled="item.useFlag === '0'"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer mes_btn">
        <el-button
          type="primary"
          @click="save">
          提交
        </el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </span>
  </el-dialog>
</template>

<script>
import tableColums from './batchScheduleCol'
export default {
  name: 'BatchSchedule',
  data() {
    return {
      tableColums: tableColums, // 表格列数据
      dialogTableVisible: false, // 弹窗是否开启
      multipleStatus: false, // 多选是否可用
      isLoading: false, // 是否加载中
      workstageList: [], // 工序列表
      saveStatus: true, // 提交按钮有效状态
      scheduleSource: {}, // 批量调度包含的工单ID、批次ID
    }
  },
  computed: {
    // 当前0点0分0秒时间戳
    todayMillisecond() {
      return this.moment(window.serverTime).startOf('day').unix() * 1000
    },
  },
  methods: {
    /**
     * 开启弹窗
     * @param list 工序列表
     */
    openDialog(list) {
      this.dialogTableVisible = true
      this.scheduleSource = {
        workorderId: list[0].workorderId,
        turnoverBatchIds: list.map(item => item.id)
      }
      this.getWorkstageMsg(this.scheduleSource)
    },
    // 获取批次工序信息
    getWorkstageMsg(postData) {
      this.isLoading = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/schedulebatch',
        data: postData,
        noCommit: true
      }).then((res) => {
        const list = res.data.turnoverWorkstage || []
        this.workstageList = list.map((item) => {
          item.workgroupId = ''
          item.workcenterId = ''
          item.staffIds = []
          item.deviceIds = []
          item.planStartDate = undefined
          item.planEndDate = undefined
          return item
        })
        this.multipleStatus = true
      }).catch(() => {
        this.dialogTableVisible = false
      }).finally(() => {
        this.isLoading = false
      })
    },
    /**
     * 开始时间输入限定（周转表/工序表）
     * @param currentEnd 工序计划完成时间（周转/工序）
     */
    getPickerOptionsStart(currentEnd) {
      let date = currentEnd || new Date()
      const minMillisecond = this.todayMillisecond
      const maxMillisecond = this.moment(date).unix() * 1000
      return {
        // 工序计划开始时间不能小于当前时间且不能大于计划完成时间
        disabledDate(time) {
          if (currentEnd) {
            return time.getTime() < minMillisecond || time.getTime() > maxMillisecond
          } else {
            return time.getTime() < minMillisecond
          }
        }
      }
    },
    /**
     * 完成时间输入限定（周转表/工序表）
     * @param currentStart 工序计划开始时间（周转/工序）
     */
    getPickerOptionsEnd(currentStart) {
      let start = this.todayMillisecond
      // 对比是否有计划开始时间以及计划开始时间是否在当前时间之后
      if (currentStart && this.moment(currentStart).isAfter(this.todayMillisecond)) {
        start = this.moment(currentStart).unix() * 1000
      }
      const minMillisecond = this.moment(start).subtract(1, 'days').unix() * 1000 + 1
      return {
        // 工序计划完成时间不能小于工序计划开始时间和当前时间
        disabledDate(time) {
          return time.getTime() < minMillisecond
        }
      }
    },
    /**
     * 解析树形子集，如选择工厂时获取所选工厂下的车间列表
     * @param {Array} list 父集列表
     * @param {String} id 所选父集元素id
     * @param {Array} field 表示子集的字段名称，如：workshops（车间）
     * @returns {Array}
     */
    parseData(list, id, field, Ids) {
      if (Array.isArray(list)) {
        if (list.find(value => value.id === id)) {
          let listArr = list.find(value => value.id === id)[field] || []
          if (Ids) {
            listArr = listArr.filter(item => Ids.some(ids => ids === item.id) || item.useFlag === '1')
          } else if (listArr[0].hasOwnProperty('useFlag')) {
            listArr = listArr.filter(item => item.useFlag === '1')
          }
          return listArr
        } else {
          return []
        }
      }
    },
    // 班组选择切换
    workgroupChange(row) {
      if (row.workgroupId) {
        row.workcenterId = ''
        row.workCenterList = this.parseData(row.nametree, row.workgroupId, 'workcenter', [row.workcenterId])
        row.deviceList = []
        row.staffList = []
        row.deviceIds = []
        row.staffIds = []
      }
    },
    // 工作中心切换
    workcenterChange(row) {
      if (row.workcenterId) {
        row.deviceIds = []
        row.staffIds = []
        row.workCenterList = this.parseData(row.nametree, row.workgroupId, 'workcenter', [row.workcenterId])
        row.deviceList = this.parseData(row.workCenterList, row.workcenterId, 'device', row.deviceIds)
        row.staffList = this.parseData(row.workCenterList, row.workcenterId, 'staff', row.staffIds)
      }
    },
    removeTagSelect(row, type) {
      if (type === 'device') {
        row.deviceList = row.deviceList.filter(item => row.deviceIds.some(id => id === item.id) || item.useFlag === '1')
      } else if (type === 'staff') {
        row.staffList = row.staffList.filter(item => row.staffIds.some(id => id === item.id) || item.useFlag === '1')
      }
    },
    // 提交调度数据
    save() {
      if (this.workstageList.some((item) => !item.workgroupId)) {
        return this.tipMessage('error', '请选择执行班组')
      }
      if (this.workstageList.some((item) => !item.workcenterId)) {
        return this.tipMessage('error', '请选择工作中心')
      }
      if (!this.saveStatus) return
      this.saveStatus = false
      let workstageData = JSON.parse(JSON.stringify(this.workstageList))
      workstageData.forEach((item) => {
        item.staffIds = item.staffIds.join(',')
        item.deviceIds = item.deviceIds.join(',')
      })
      const postData = {
        turnoverWorkstageList: workstageData,
        ...this.scheduleSource
      }
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/savebatchdispatch',
        data: postData,
        noCommit: true
      }).then(() => {
        this.dialogTableVisible = false
        this.tipMessage('success', '提交成功')
        this.$emit('submitSuccess')
      }).catch(() => {
        this.saveStatus = true
      })
    },
    // 弹窗关闭回调函数
    closedDialog() {
      this.workstageList = []
      this.multipleStatus = false
      this.saveStatus = true
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .workstage_scdu{
    .el-date-editor--date input{
      padding: 0 20px!important;
    }
    .el-table__body td .el-input__prefix {
      left: -6px;
    }
  }
</style>
